<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文章来源" prop="articleOrigin">
        <el-input
          v-model="queryParams.articleOrigin"
          placeholder="请输入文章来源"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="栏目名称" prop="columnId">
        <el-select v-model="queryParams.columnId" placeholder="请选择栏目名称"
            clearable
            filterable
            @change="handleColumnChange"
            >
            <el-option
              v-for="item in columnOptions"
              :key="item.columnId"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
      </el-form-item>
      <el-form-item label="责任编辑" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入责任编辑"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="新闻正文" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入正文部分内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="发布日期">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px"
        />
      </el-form-item>


      <el-form-item label="显示状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择"
                   clearable
                   style="width: 160px;"
        >
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['article:article:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['article:article:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteData"
          v-hasPermi="['article:article:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['article:article:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-view"
          size="mini"
          :disabled="multiple"
          @click="handleBatchHide"
          v-hasPermi="['article:article:edit']"
        >批量隐藏</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-refresh"
          size="mini"
          :disabled="multiple"
          @click="handleBatchShow"
          v-hasPermi="['article:article:edit']"
        >批量显示</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-search"
          size="mini"
          @click="handleBatchByCondition"
          v-hasPermi="['article:article:edit']"
        >按条件批量操作</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-document"
          size="mini"
          @click="handleOpenDraftBox"
        >草稿箱</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="id" align="center" width="50" prop="articleId" />
      <el-table-column label="标题" align="center" width="250" prop="title" />
      <el-table-column label="文章来源" align="center" width="100" prop="articleOrigin" />
      <el-table-column label="栏目名称" align="center" width="100" prop="name" />
<!--      <el-table-column label="内容" align="center" prop="content" width="300" :formatter="formatContent"/>-->
      <el-table-column label="内容" align="center" prop="content" width="300">
        <template slot-scope="scope">
          <div class="content-cell">{{ formatContent(scope.row.content) }}</div>
        </template>
      </el-table-column>
      <el-table-column label="责任编辑" align="center" width="100" prop="author" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <!-- <el-table-column label="封面路径" align="center" prop="coverPath" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverPath" :width="50" :height="50"/>
        </template>
      </el-table-column> -->
      <el-table-column label="发布日期" align="center" prop="pubdate" width="120" />
      <el-table-column label="审批表" align="center" prop="appval" width="100">
          <template slot-scope="scope">
            <image-preview :src="scope.row.appval" :width="50" :height="50"/>
          </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['article:article:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteData(scope.row)"
            v-hasPermi="['article:article:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleHide(scope.row)"
            v-if="scope.row.status !== 1"
          >隐藏</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleShow(scope.row)"
            v-if="scope.row.status === 1"
          >显示</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-transfer"
            @click="handleTransferToNews(scope.row)"
          >转到河道要闻</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-transfer"
            @click="handleTransferToToutiao(scope.row)"
          >转到头条</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改artilce对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <enhanced-editor v-model="form.title" :min-height="120" :max-height="200" placeholder="请输入内容"/>
        </el-form-item>

        <!-- 副标题部分 -->
        <el-form-item label="副标题">
          <div v-for="(subtitle, index) in subtitles" :key="index" class="subtitle-item">
          <enhanced-editor v-model="form[`littleTitle${index + 1}`]" :placeholder="`请输入副标题${index + 1}`"  :min-height="120" :max-height="200" />
          </div>
          <el-button
            v-if="subtitles.length < 2"
            type="text"
            icon="el-icon-plus"
            @click="addSubtitle"
          >
            添加副标题
          </el-button>
        </el-form-item>
        <el-form-item label="文章来源" prop="articleOrigin">
          <el-autocomplete
            v-model="form.articleOrigin"
            :fetch-suggestions="querySearchSource"
            placeholder="请输入文章来源"
            clearable
            style="width: 223px;"
          />
        </el-form-item>
        <el-form-item label="栏目名称" prop="name">
          <el-select v-model="form.name" placeholder="请选择栏目名称"
            clearable
            filterable
             @change="handleColumnChange"
            :key="selectKey"
          >
            <el-option
              v-for="item in columnOptions"
              :key="item.columnId"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <!-- 不显示责任编辑 -->
        <el-form-item label="责任编辑" prop="author">
          <el-autocomplete
            v-model="form.author"
            :fetch-suggestions="querySearchAuthor"
            placeholder="请输入责任编辑"
            clearable
            style="width: 223px;"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-form-item label="封面路径" prop="coverPath">-->
<!--          <image-upload v-model="form.coverPath"/>-->
<!--        </el-form-item>-->
        <!-- <el-form-item label="封面路径" prop="coverPath">
          <el-upload
            ref="upload"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :on-remove="handleRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传封面图片，大小不超过10MB</div>
          </el-upload>
        </el-form-item> -->

        <!-- <el-form-item label="审批表" prop="appval">
          <image-upload v-model="form.appval"/>
        </el-form-item> -->

        <el-form-item label="审批表" prop="appval">
          <el-upload
            ref="appvalUpload"
            :file-list="appvalFileList"
            :before-upload="beforeAppvalUpload"
            :on-change="handleAppvalFileChange"
            :auto-upload="false"
            :on-remove="handleAppvalRemove"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleAppvalHttpRequest"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">请上传审批表图片</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="附件" prop="attachment">
          <el-upload
            ref="attachmentUpload"
            :file-list="attachmentFileList"
            :before-upload="beforeAttachmentUpload"
            :on-change="handleAttachmentFileChange"
            :auto-upload="false"
            :on-remove="handleAttachmentRemove"
            :limit="1"
            list-type="text"
            action="#"
            :http-request="handleAttachmentHttpRequest"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button
              v-if="form.attachment || temporaryAttachmentUrl"
              size="small"
              type="success"
              icon="el-icon-download"
              @click.stop="downloadAttachment(form.attachment || temporaryAttachmentUrl, getAttachmentFileName(form.attachment || temporaryAttachmentUrl))"
              style="margin-left: 10px;"
            >
              下载附件
            </el-button>
            <div slot="tip" class="el-upload__tip">请上传附件文件</div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <!-- 编辑草稿时显示更新草稿、直接发布、取消按钮 -->
        <template v-if="title === '修改草稿'">
          <el-button type="primary" @click="handleUpdateDraft">更新草稿</el-button>
          <el-button type="success" class="draft-publish-button" @click="handlePublishFromDraft">直接发布</el-button>
          <el-button @click="cancel">取消</el-button>
        </template>
        <!-- 编辑正式文章时显示确定、保存草稿、取消按钮 -->
        <template v-else>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button type="warning" class="draft-save-button" @click="handleSaveDraft">保存草稿</el-button>
          <el-button @click="cancel">取 消</el-button>
        </template>
      </div>
    </el-dialog>

    <!-- 封面图片选择对话框 -->
    <el-dialog :visible.sync="coverDialogVisible" title="选择或上传封面图片" width="800px">
      <el-row :gutter="20">
        <!-- 从文章内容中选择图片 -->
        <el-col :span="12">
          <div class="cover-section-title">从文章中选择</div>
          <div v-if="articleImages.length > 0" class="image-list">
            <div
              v-for="(image, index) in articleImages"
              :key="index"
              class="image-item"
              :class="{ selected: selectedCoverImage === image }"
              @click="selectCoverImage(image)"
            >
              <img :src="image" alt="封面图片" class="cover-preview" />
            </div>
          </div>
          <div v-else class="no-image-tip">
            文章内容中没有图片，请手动上传封面。
          </div>
        </el-col>

        <!-- 手动上传图片 -->
        <el-col :span="12">
          <div class="cover-section-title">手动上传</div>
          <el-upload
            ref="manualCoverUpload"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            :auto-upload="false"
            :limit="1"
            list-type="picture-card"
            accept="image/*"
            action="#"
            :http-request="handleHttpRequest"
            :file-list="fileList"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip">请上传封面图片，大小不小于1MB</div>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="coverDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCoverSelection">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 按条件批量操作对话框 -->
    <el-dialog :title="'按条件批量操作'" :visible.sync="batchDialogVisible" width="500px" append-to-body>
      <el-form label-width="120px">
        <el-form-item label="操作类型：">
          <el-radio-group v-model="batchOperation">
            <el-radio label="hide">批量隐藏</el-radio>
            <el-radio label="show">批量显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-alert
          :title="`将按当前查询条件批量${batchOperation === 'hide' ? '隐藏' : '显示'}文章`"
          type="info"
          show-icon
          :closable="false"
        >
        </el-alert>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBatchOperation">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 草稿箱对话框 -->
    <el-dialog title="草稿箱" :visible.sync="draftBoxVisible" width="80%" append-to-body>
      <el-table v-loading="draftLoading" :data="draftList" @selection-change="handleSelectionChange">
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="文章来源" align="center" prop="articleOrigin" />
        <el-table-column label="栏目名称" align="center" prop="name" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="审批表" align="center" prop="appval" width="100">
          <template slot-scope="scope">
            <span :class="scope.row.appval && scope.row.appval !== '' ? 'has-approval' : 'no-approval'">
              {{ scope.row.appval && scope.row.appval !== '' ? '已上传' : '未上传' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEditDraft(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-check"
              @click="handlePublishDraft(scope.row)"
            >发布</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDeleteDraft(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="draftBoxVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listConlumn,getConlumn,listConlumnList} from "@/api/conlumn/conlumn";
import { uploadFile,uploadAppval,uploadContentImage,uploadAttachment } from "@/api/article/article";
import { listArticle, getArticle, delArticle, addArticle, updateArticle } from "@/api/article/article";
import { addRiver_news,listRiver_news } from "../../api/river_news/river_news";
import {listToutiao,delToutiao,addToutiao} from "../../api/toutiao/toutiao";
import { time } from "echarts";
import imageCompression from "browser-image-compression";
import { logicDeleteArticle} from "../../api/article/article";
import { hideArticle,showArticle,batchHideArticle,batchShowArticle,batchHideArticleByCondition,batchShowArticleByCondition} from "@/api/article/article";
import { saveDraft, updateDraft, publishDraft, listDraft } from "@/api/article/article";
import { delDraft, getDraft } from "@/api/draft";
import EnhancedEditor from "@/components/Editor/EnhancedEditor.vue";


export default {
  name:"Article",
  dicts: ['status'],
  components: {
    EnhancedEditor
  },
  data() {
    return {
      transferRow: null, //原始文章行数据
      coverDialogVisible: false, // 控制封面图片选择对话框的显示
      coverSelectTab: 'select',  // 封面选择标签页
      articleImages: [],         // 文章内容中的图片列表
      selectedCoverImage: null,  // 用户选择的封面图片

      subtitles: [], // 用于存储副标题的动态数量
      appvalFileList: [],      // 审批表文件列表
      uploadAppvalFile: null,  // 待上传的审批表文件
      attachmentFileList: [],      // 附件文件列表
      uploadAttachmentFile: null,  // 待上传的附件文件
      temporaryAttachmentUrl: null,  // 临时附件URL（用于预览）

      // 独立的审批表状态管理字段
      appvalState: {
        currentUrl: null, // 当前审批表URL
        pendingFile: null, // 待上传的审批表文件
        isRemoved: false, // 是否被用户移除
        originalUrl: null, // 原始审批表URL（用于比较是否发生变化）
      },

      uploadRes:[],
      fileList: [],
      uploadFile: null,

      // 防止重复提交标志
      isSubmitting: false,

      // 日期范围
      dateRange: [],

      //部门名称
      dept: null,

      showLineLengthWarning:'',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // artilce表格数据
      articleList: [],
      columnOptions:[],
      //用户名称
      userName: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        articleOrigin: null,
        columnId: null,
        author: null,
        status: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "标题不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "栏目名称不能为空", trigger: "blur"}
        ],
        content: [
          {required: true, message: "内容不能为空", trigger: "blur"}
        ],
        articleName:'',
        canAdd: false,//是否显示添加头条，河道要闻操作按钮
      },

      // 文章来源历史记录（市局用户输入记忆功能）- 使用固定大小为10的循环缓冲区
      sourceHistory: [],
      // 责任编辑历史记录 - 使用固定大小为10的循环缓冲区
      authorHistory: [],
      selectKey: 0, // 用于强制重新渲染 el-select

      // 按条件批量操作相关数据
      batchDialogVisible: false,
      batchOperation: 'hide', // 'hide' 或 'show'

      // 草稿箱相关数据
      draftBoxVisible: false,
      draftList: [],
      draftLoading: false
    };
  },
  created() {
    this.getColumnList();
    this.getList();
    // 加载文章来源历史记录
    const storedHistory = localStorage.getItem('sourceHistory');
    if (storedHistory) {
      const historyData = JSON.parse(storedHistory);
      // 过滤掉超过3天的数据
      const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);

      this.sourceHistory = historyData.filter(item => item.timestamp > thirtyDaysAgo)
        .map(item => item.value);
    }

    // 加载责任编辑历史记录
    const storedAuthorHistory = localStorage.getItem('authorHistory');
    if (storedAuthorHistory) {
      const authorHistoryData = JSON.parse(storedAuthorHistory);
      // 过滤掉超过3天的数据
      const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);

      this.authorHistory = authorHistoryData.filter(item => item.timestamp > thirtyDaysAgo)
        .map(item => item.value);
    }
  },
  watch: {
    'form.title'(newVal) {
      this.checkLineLength();
    },
    columnOptions: {
      handler(newVal) {
        if (newVal.length > 0 && this.form?.columnId) {
          const column = newVal.find(item => item.id === this.form.columnId);
          this.form.name = column ? column.name : '';
          this.articleName = this.form.name; // 同步 articleName
        }
      },
      deep: true,
      immediate: true
    }
  },

  methods: {

    /**
     * 按条件批量操作
     */
    handleBatchByCondition() {
      // 显示批量操作对话框
      this.batchDialogVisible = true;
    },

    /**
     * 确认批量操作
     */
    confirmBatchOperation() {
      const operationText = this.batchOperation === 'hide' ? '隐藏' : '显示';
      this.$modal.confirm(`是否确认按当前查询条件批量${operationText}文章？`).then(() => {
        // 构造查询参数
        const params = {
          ...this.queryParams,
          // 添加日期范围参数
          beginPubdate: this.dateRange && this.dateRange.length === 2 ? this.dateRange[0] : undefined,
          endPubdate: this.dateRange && this.dateRange.length === 2 ? this.dateRange[1] : undefined
        };

        // 调用后端接口执行批量操作
        if (this.batchOperation === 'hide') {
          return batchHideArticleByCondition(params);
        } else {
          return batchShowArticleByCondition(params);
        }
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("批量操作成功");
        this.batchDialogVisible = false;
      }).catch(() => {
        // 用户取消操作
      });
    },

    /**
     * 确认封面选择
     */
    confirmCoverSelection() {
      // 如果用户选择了文章内容中的图片
      if (this.selectedCoverImage) {
        this.coverDialogVisible = false;
        this.uploadCoverImage(this.selectedCoverImage);
      }
      // 如果用户手动上传了封面图片
      else if (this.uploadFile) {
        this.coverDialogVisible = false;
        // 检查是否为OSS图片URL
        if (this.uploadFile.url) {
          // 对于OSS图片，直接使用URL
          this.form.coverPath = this.uploadFile.url;
          this.$message.success('封面图片设置成功');

          // 如果是在转到河道要闻的过程中上传封面，则继续执行转到河道要闻的逻辑
          if (this.transferRow) {
            this.doAddRiverNewsAfterCoverUpload(this.transferRow);
          }
        } else {
          console.log('提交前压缩封面图片');
          this.compressImage(this.uploadFile).then(compressedFile => {
            this.uploadFile = compressedFile;
            this.uploadFileToServer(this.uploadFile);
          }).catch(error => {
            console.error('压缩图片失败:', error);
            this.$message.error('压缩图片失败: ' + error.message);
          });
        }
      } else {
        this.$modal.msgError("请选择或上传封面图片！");
      }
    },

    /**
     * 从文章内容中提取图片 URL
     */
    extractImagesFromContent(content) {
      const imgRegex = /<img[^>]+src="([^">]+)"/g;
      const matches = content.match(imgRegex);
      if (!matches) return [];

      return matches.map(match => {
        const srcMatch = match.match(/src="([^">]+)"/);
        return srcMatch ? srcMatch[1] : null;
      }).filter(src => src); // 过滤掉无效的 URL
    },

    addSubtitle() {
      if (this.subtitles.length < 2) {
        this.subtitles.push(`littleTitle${this.subtitles.length + 1}`);
      }
    },

   // 使用 Canvas 进行图片压缩，可以更精确地控制文件大小
    async compressImage(file, checkMinSize = true) {
      const minSizeBytes = 1024 * 1024; // 1MB 下限
      const maxSizeBytes = 5 * 1024 * 1024; // 5MB 上限
      const skipCompressSizeBytes = 3 * 1024 * 1024; // 3MB

      // 检查文件是否小于最小大小（仅当checkMinSize为true时检查）
      if (checkMinSize && file.size < minSizeBytes) {
        throw new Error('图片大小不能小于1MB!');
      }

      // 如果文件小于 3MB，直接跳过压缩
      if (file.size < skipCompressSizeBytes) {
        console.log(`文件大小为 ${file.size} bytes，小于 3MB，跳过压缩`);
        return file;
      }

      // 所有图片都使用 Canvas 进行精确压缩，确保不会低于下限
      return await this.canvasCompress(file, minSizeBytes, maxSizeBytes);
    },

    // 使用 Canvas 进行精确压缩
    async canvasCompress(file, minSizeBytes, maxSizeBytes) {
      return new Promise((resolve, reject) => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const img = new Image();

        img.onload = async () => {
          // 初始宽高
          let width = img.width;
          let height = img.height;

          // 计算缩放比例
          const ratio = width / height;

          // 如果图片很大，先进行初步缩放
          if (width > 2048 || height > 2048) {
            if (width > height) {
              width = 2048;
              height = 2048 / ratio;
            } else {
              height = 2048;
              width = 2048 * ratio;
            }
          }

          // 设置 canvas 尺寸
          canvas.width = width;
          canvas.height = height;

          // 绘制图片到 canvas
          ctx.drawImage(img, 0, 0, width, height);

          // 二分法查找合适的质量参数
          let quality = 1;
          let minQuality = 0.1;
          let maxQuality = 2;
          let attempts = 0;
          const maxAttempts = 10;

          let compressedBlob;

          while (attempts < maxAttempts) {
            attempts++;

            // 导出为 Blob
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', quality);
            });

            console.log(`第 ${attempts} 次压缩尝试，质量: ${quality}, 大小: ${compressedBlob.size} bytes`);

            // 检查大小是否符合要求
            if (compressedBlob.size >= minSizeBytes && compressedBlob.size <= maxSizeBytes) {
              console.log('压缩成功，大小符合要求');
              break;
            }

            // 调整质量参数
            if (compressedBlob.size > maxSizeBytes) {
              // 太大了，降低质量
              maxQuality = quality;
              quality = (minQuality + quality) / 2;
            } else {
              // 太小了，提高质量
              minQuality = quality;
              quality = (quality + maxQuality) / 2;
            }

            // 如果质量调整过小，可能无法达到最小大小要求
            if (quality < 0.01) {
              console.warn('质量参数过低，无法达到最小大小要求');
              break;
            }
          }

          // 如果最终结果还是太小，使用最小质量重新压缩
          if (compressedBlob.size < minSizeBytes) {
            console.warn(`压缩后文件过小 (${compressedBlob.size} bytes)，使用最小质量重新压缩`);
            compressedBlob = await new Promise(resolve => {
              canvas.toBlob(resolve, 'image/jpeg', 0.95);
            });
          }

          // 转换为 File 对象
          const compressedFile = new File([compressedBlob], file.name, {
            type: 'image/jpeg',
            lastModified: Date.now()
          });

          console.log(`最终压缩结果: ${compressedFile.size} bytes`);
          resolve(compressedFile);
        };

        img.onerror = () => {
          reject(new Error('图片加载失败'));
        };

        // 读取文件
        const reader = new FileReader();
        reader.onload = e => {
          img.src = e.target.result;
        };
        reader.onerror = () => {
          reject(new Error('文件读取失败'));
        };
        reader.readAsDataURL(file);
      });
    },

    // 审批表上传请求处理
    handleAppvalHttpRequest(options) {

      this.uploadAppvalToServer(options.file);
    },

    // 上传审批表文件到服务器
    async uploadAppvalToServer(file) {
       // 确保传入的是有效的文件对象
      if (!file || !(file instanceof File)) {
        console.error('无效的文件对象:', file);
        this.$message.error('审批表文件无效');
        return;
      }

      const formData = new FormData();
      formData.append('appvalPath', file);

      try {
        //console.log('调用审批表上传API，ID:', this.form.articleId || 0);
        const response = await uploadAppval(this.form.articleId || 0, formData);
        //console.log('审批表上传响应:', response);
        if (response.code === 200) {
          this.form.appval = response.url;
          this.$message.success('审批表上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('审批表上传失败:', error);
        this.$message.error('审批表上传失败: ' + error.message);
        throw error;
      }
    },

    // 审批表文件上传前处理
    beforeAppvalUpload(file) {
      const isImage = file.type.startsWith('image/');

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }

      this.uploadAppvalFile = file;
      console.log('设置 uploadAppvalFile:', this.uploadAppvalFile);
      return false; // 阻止自动上传
    },

    // 审批表文件变化处理
    handleAppvalFileChange(file, fileList) {
      console.log('审批表文件变化处理:', file, fileList);
      if (fileList.length > 0) {
        this.uploadAppvalFile = fileList[0].raw;
        this.appvalFileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
        console.log('设置 uploadAppvalFile:', this.uploadAppvalFile);

        // 更新审批表状态
        this.appvalState.pendingFile = fileList[0].raw;
        this.appvalState.isRemoved = false;
      } else {
        this.uploadAppvalFile = null;
        this.appvalFileList = [];
        // 标记为已移除并清空form.appval
        this.appvalState.isRemoved = true;
        this.form.appval = null; // 清空表单中的审批表URL
        this.appvalState.pendingFile = null;
        console.log('标记审批表为已移除');
      }
    },

    // 审批表文件移除处理
    handleAppvalRemove() {
      console.log('审批表文件移除处理');
      console.log('移除前状态:', {
        uploadAppvalFile: this.uploadAppvalFile,
        isRemoved: this.appvalState.isRemoved,
        currentUrl: this.appvalState.currentUrl,
        originalUrl: this.appvalState.originalUrl,
        formAppval: this.form.appval
      });
      this.uploadAppvalFile = null;
      // 标记为已移除并清空form.appval
      this.appvalState.isRemoved = true;
      this.form.appval = null; // 清空表单中的审批表URL
      this.appvalFileList = [];
      console.log('标记审批表为已移除');
      console.log('移除后状态:', {
        isRemoved: this.appvalState.isRemoved,
        currentUrl: this.appvalState.currentUrl,
        originalUrl: this.appvalState.originalUrl,
        formAppval: this.form.appval
      });
    },

    // 附件上传请求处理
    async handleAttachmentHttpRequest(options) {
      try {
        const response = await this.uploadAttachmentToServer(options.file);
        if (response && response.code === 200 && response.url) {
          // 设置文件的URL，使Element UI上传组件能够显示可点击的文件链接
          const fileData = {
            name: options.file.name,
            url: response.url
          };
          options.onSuccess(fileData);
        } else {
          options.onError(new Error(response.msg || '上传失败'));
        }
      } catch (error) {
        options.onError(error);
      }
    },

    // 上传附件文件到服务器
    async uploadAttachmentToServer(file) {
      // 确保传入的是有效的文件对象
      if (!file || !(file instanceof File)) {
        console.error('无效的文件对象:', file);
        this.$message.error('附件文件无效');
        return;
      }

      const formData = new FormData();
      formData.append('file', file);

      try {
        const response = await uploadAttachment(this.form.articleId || 0, formData);
        if (response.code === 200) {
          this.form.attachment = response.url;
          this.$message.success('附件上传成功');
          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('附件上传失败:', error);
        this.$message.error('附件上传失败: ' + error.message);
        throw error;
      }
    },

    // 附件文件上传前处理
    beforeAttachmentUpload(file) {
      this.uploadAttachmentFile = file;
      console.log('设置 uploadAttachmentFile:', this.uploadAttachmentFile);
      return false; // 阻止自动上传
    },

    // 附件文件变化处理
    async handleAttachmentFileChange(file, fileList) {
      console.log('附件文件变化处理:', file, fileList);
      if (fileList.length > 0) {
        this.uploadAttachmentFile = fileList[0].raw;
        this.attachmentFileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
        console.log('设置 uploadAttachmentFile:', this.uploadAttachmentFile);

        // 立即上传附件文件，但不保存到数据库
        if (this.uploadAttachmentFile && this.uploadAttachmentFile instanceof File) {
          try {
            const response = await this.uploadAttachmentToServer(this.uploadAttachmentFile);
            if (response && response.code === 200 && response.url) {
              // 保存上传后的URL，但不立即更新到form.attachment
              this.temporaryAttachmentUrl = response.url;
              // 更新文件列表显示
              this.attachmentFileList = [{
                name: this.uploadAttachmentFile.name,
                url: response.url
              }];
              this.$message.success('附件上传成功，可点击下载预览');
            }
          } catch (error) {
            console.error('附件上传失败:', error);
            this.$message.error('附件上传失败: ' + error.message);
          }
        }
      } else {
        this.uploadAttachmentFile = null;
        this.attachmentFileList = [];
        this.temporaryAttachmentUrl = null; // 清空临时URL
        console.log('清空 uploadAttachmentFile');
      }
    },

    // 附件文件移除处理
    handleAttachmentRemove(file, fileList) {
      console.log('附件文件移除处理:', file, fileList);
      this.uploadAttachmentFile = null;
      this.form.attachment = null; // 清空表单中的附件URL
      this.temporaryAttachmentUrl = null; // 清空临时附件URL
      this.attachmentFileList = fileList || [];
      console.log('清空 uploadAttachmentFile 和 attachment');
    },


    // 获取附件文件名
    getAttachmentFileName(url) {
      if (!url) return '';
      const fileName = url.substring(url.lastIndexOf('/') + 1);
      // 移除查询参数
      return fileName.split('?')[0];
    },

    // 下载附件
    downloadAttachment(url, fileName) {
      if (!url) {
        this.$message.warning('附件链接无效');
        return;
      }

      // 创建隐藏的下载链接
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName || this.getAttachmentFileName(url);
      link.style.display = 'none';

      // 添加到文档中并触发点击
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
    },


    /** 处理审批表上传 */
    async handleAppvalUpload() {
      try {
        // 检查是否有新的审批表文件需要上传
        if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
          console.log('处理审批表上传');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);
          const response = await this.uploadAppvalToServer(this.uploadAppvalFile);

          // 更新审批表状态
          if (response && response.url) {
            this.appvalState.currentUrl = response.url;
            this.appvalState.pendingFile = null;
            this.appvalState.isRemoved = false;
            this.appvalState.originalUrl = response.url; // 同步originalUrl
            this.form.appval = response.url; // 确保form.appval也被更新

            // 独立验证审批表上传结果
            console.log('审批表上传成功，验证状态同步:', {
              currentUrl: this.appvalState.currentUrl,
              originalUrl: this.appvalState.originalUrl,
              formAppval: this.form.appval
            });

            // 额外验证状态同步
            if (this.appvalState.currentUrl !== response.url || this.form.appval !== response.url) {
              console.warn('审批表状态同步可能存在延迟，强制同步状态');
              this.appvalState.currentUrl = response.url;
              this.appvalState.originalUrl = response.url;
              this.form.appval = response.url;
            }
          }

          console.log('审批表上传完成，更新状态:', {
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved,
            formAppval: this.form.appval
          });

          return true;
        }
        // 检查用户是否移除了审批表
        else if (this.appvalState.isRemoved) {
          console.log('用户移除了审批表，清空appval字段');
          this.form.appval = null;
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
          return true;
        }
        // 如果没有变化，跳过上传
        else {
          console.log('跳过审批表上传 - 无变化');
          console.log('当前审批表状态:', {
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved,
            formAppval: this.form.appval
          });
          return true;
        }
      } catch (error) {
        console.error('审批表上传失败:', error);
        this.$message.error('审批表上传失败: ' + error.message);
        throw error;
      }
    },

    /** 检查是否需要上传审批表 */
    needUploadAppval() {
      console.log('检查是否需要上传审批表:', {
        uploadAppvalFile: this.uploadAppvalFile,
        isFile: this.uploadAppvalFile instanceof File,
        isRemoved: this.appvalState.isRemoved,
        originalUrl: this.appvalState.originalUrl,
        currentUrl: this.appvalState.currentUrl,
        formAppval: this.form.appval
      });

      // 检查是否有新的审批表文件待上传
      if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
        console.log('需要上传：有新的审批表文件待上传');
        return true;
      }

      // 检查用户是否移除了审批表
      if (this.appvalState.isRemoved && this.appvalState.originalUrl) {
        console.log('需要上传：用户移除了审批表');
        return true;
      }

      // 检查URL是否发生变化
      if (this.appvalState.currentUrl !== this.appvalState.originalUrl) {
        console.log('需要上传：URL发生变化');
        console.log('currentUrl:', this.appvalState.currentUrl, 'originalUrl:', this.appvalState.originalUrl);
        return true;
      }

      // 检查表单中的appval字段是否与当前URL不一致
      if (this.form.appval && this.form.appval !== this.appvalState.currentUrl) {
        console.log('需要上传：表单appval与当前URL不一致');
        console.log('form.appval:', this.form.appval, 'currentUrl:', this.appvalState.currentUrl);
        return true;
      }

      console.log('不需要上传审批表');
      return false;
    },

    /** 检查审批表是否有效 */
    isValidAppval() {
      console.log('检查审批表是否有效:', {
        formAppval: this.form.appval,
        currentUrl: this.appvalState.currentUrl,
        uploadAppvalFile: this.uploadAppvalFile,
        isFile: this.uploadAppvalFile instanceof File,
        originalUrl: this.appvalState.originalUrl,
        isRemoved: this.appvalState.isRemoved
      });

      // 如果用户明确移除了审批表，则无效（但在保存草稿时应允许）
      if (this.appvalState.isRemoved) {
        console.log('审批表无效：用户已移除审批表');
        return false;
      }

      // 检查表单中的appval字段
      if (this.form.appval && this.form.appval !== "") {
        console.log('审批表有效：表单中有appval字段');
        return true;
      }

      // 检查当前审批表URL
      if (this.appvalState.currentUrl && this.appvalState.currentUrl !== "") {
        console.log('审批表有效：当前有审批表URL');
        // 同步form.appval与currentUrl
        this.form.appval = this.appvalState.currentUrl;
        return true;
      }

      // 检查原始审批表URL
      if (this.appvalState.originalUrl && this.appvalState.originalUrl !== "") {
        console.log('审批表有效：有原始审批表URL');
        // 同步form.appval与originalUrl
        this.form.appval = this.appvalState.originalUrl;
        return true;
      }

      // 检查是否有待上传的审批表文件
      if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
        console.log('审批表有效：有待上传的审批表文件');
        return true;
      }

      // 特殊情况处理：如果form.appval为空但originalUrl不为空，说明审批表已存在
      if (!this.form.appval && this.appvalState.originalUrl) {
        console.log('审批表有效：使用原始审批表URL');
        // 同步form.appval与originalUrl
        this.form.appval = this.appvalState.originalUrl;
        return true;
      }

      console.log('审批表无效');
      return false;
    },

    /** 专门处理审批表上传和验证的独立流程 */
    async handleAppvalUploadAndValidate() {
      try {
        console.log('开始独立审批表上传和验证流程');

        // 检查是否有新的审批表文件需要上传
        if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
          console.log('检测到新的审批表文件，开始处理');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);

          // 上传审批表
          const response = await this.uploadAppvalToServer(this.uploadAppvalFile);

          // 更新审批表状态
          if (response && response.url) {
            console.log('审批表上传成功:', response.url);
            this.appvalState.currentUrl = response.url;
            this.appvalState.pendingFile = null;
            this.appvalState.isRemoved = false;
            this.appvalState.originalUrl = response.url;
            this.form.appval = response.url;

            // 强制同步状态
            this.$forceUpdate();
            await this.$nextTick();

            console.log('审批表状态已更新:', {
              currentUrl: this.appvalState.currentUrl,
              originalUrl: this.appvalState.originalUrl,
              formAppval: this.form.appval
            });
          }
        }
        // 检查用户是否移除了审批表
        else if (this.appvalState.isRemoved) {
          console.log('用户移除了审批表');
          this.form.appval = null;
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
        }
        // 如果已有审批表，确保状态同步
        else if (this.appvalState.originalUrl && !this.form.appval) {
          console.log('同步已有审批表状态');
          this.form.appval = this.appvalState.originalUrl;
        }

        // 验证审批表是否有效
        const isValid = this.isValidAppval();
        console.log('审批表验证结果:', isValid);

        if (!isValid) {
          console.log('审批表无效，详细状态:', {
            formAppval: this.form.appval,
            currentUrl: this.appvalState.currentUrl,
            originalUrl: this.appvalState.originalUrl,
            isRemoved: this.appvalState.isRemoved
          });
        }

        return isValid;
      } catch (error) {
        console.error('独立审批表上传和验证流程失败:', error);
        return false;
      }
    },

    handleEnterKey(e) {
      if (!e.ctrlKey && !e.shiftKey) {
        e.preventDefault();
        const textarea = e.target;
        const start = textarea.selectionStart;
        const end = textarea.selectionEnd;
        this.form.title = this.form.title.substring(0, start) + '\n' + this.form.title.substring(end);
        this.$nextTick(() => {
          textarea.selectionStart = textarea.selectionEnd = start + 1;
          this.checkLineLength(); // 换行后立即检查
        });
      }
    },

    checkLineLength() {
      // 检查每一行是否超过24个字符
      const lines = this.form.title.split('\n');
      this.showLineLengthWarning = lines.some(line => line.length > 24);

      // 如果用户已经换行但仍有超长行，继续显示警告
      if (this.showLineLengthWarning) {
        this.$nextTick(() => {
          const textarea = this.$el.querySelector('textarea');
          if (textarea) {
            textarea.style.borderColor = '#f56c6c';
          }
        });
      } else {
        this.$nextTick(() => {
          const textarea = this.$el.querySelector('textarea');
          if (textarea) {
            textarea.style.borderColor = '';
          }
        });
      }
    },

    formatContent(content) {
      // 先移除HTML标签
      const plainText = content.replace(/<[^>]*>/g, '');
      // 截取前100个字符（可根据需要调整）
      return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText;
    },

    // 格式化时间显示
    formatDateTime(datetime) {
      if (!datetime) return '';
      // 如果是字符串格式的时间
      if (typeof datetime === 'string') {
        // 处理ISO 8601格式的时间字符串
        if (datetime.includes('T')) {
          const date = new Date(datetime);
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          const hours = String(date.getHours()).padStart(2, '0');
          const minutes = String(date.getMinutes()).padStart(2, '0');
          const seconds = String(date.getSeconds()).padStart(2, '0');
          return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        return datetime;
      }
      // 如果是Date对象，格式化为YYYY-MM-DD HH:mm:ss
      const year = datetime.getFullYear();
      const month = String(datetime.getMonth() + 1).padStart(2, '0');
      const day = String(datetime.getDate()).padStart(2, '0');
      const hours = String(datetime.getHours()).padStart(2, '0');
      const minutes = String(datetime.getMinutes()).padStart(2, '0');
      const seconds = String(datetime.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    /** 查询栏目列表 */
    getColumnList() {
      listConlumnList().then(response => {
        this.columnOptions = response.rows;
      });
    },
  /** 查询artilce列表 */
  // getList() {
  //   this.loading = true;
  //   listArticle(this.queryParams).then(response => {
  //     const { rows, total } = response.data; // 从 response.data 中提取 rows 和 total
  //     this.canAdd = response.canAdd;         //设置 canAdd 权限字段
  //     this.userName = response.userName;
  //
  //     //处理栏目名称映射
  //     this.articleList = rows.map(item => {
  //         const conlumn = this.columnOptions.find(col => col.id === item.columnId);
  //         return {
  //           ...item,
  //           name: conlumn ? conlumn.name : '未知栏目',
  //         };
  //       });
  //
  //
  //
  //     this.total = total;
  //     this.loading = false;
  //   }).catch(error => {
  //     console.error('获取文章列表失败:', error);
  //     this.loading = false;
  //   });
  // },
  getList() {
    this.loading = true;
    // 克隆queryParams以避免直接修改
    const params = {
      ...this.queryParams,
      // 确保content作为整体传递
      content: this.queryParams.content || undefined
    };


      listArticle(params).then(response => {
        const { rows, total } = response.data; // 从 response.data 中提取 rows 和 total
        this.canAdd = response.canAdd;         //设置 canAdd 权限字段
        this.userName = response.userName;

        if(this.canAdd)
        {
          this.dept = null;
        }
        else
        {
          this.dept = response.dept;
        }


        //处理栏目名称映射
        this.articleList = rows.map(item => {
            const conlumn = this.columnOptions.find(col => col.id === item.columnId);
            return {
              ...item,
              name: conlumn ? conlumn.name : '未知栏目',
            };
          });



        this.total = total;
        this.loading = false;
      }).catch(error => {
        console.error('获取文章列表失败:', error);
        this.loading = false;
      });
  },
  // 取消按钮
  cancel() {
    this.open = false;
    this.reset();
  },
  // 表单重置
  reset() {
    this.form = {
      articleId: null,
      title: null,
      articleOrigin: null,
      columnId: null,
      content: null,
      author: null,
      createTime: null,
      createBy: null,
      updateTime: null,
      updateBy: null,
      remark: null,
      name: null,
      coverPath: null,
      appval: null,
      littleTitle1: null, // 清空副标题1
      littleTitle2: null, // 清空副标题2
      attachment: null, // 清空附件
    };
    this.subtitles = []; // 清空副标题数组

    // 重置附件相关字段
    this.attachmentFileList = [];      // 附件文件列表
    this.uploadAttachmentFile = null;  // 待上传的附件文件
    this.temporaryAttachmentUrl = null;  // 临时附件URL（用于预览）

    // 重置审批表相关字段
    this.appvalFileList = [];          // 审批表文件列表
    this.appvalState = {
      currentUrl: null,                // 当前审批表URL
      pendingFile: null,               // 待上传的审批表文件
      isRemoved: false,                // 是否被用户移除
      originalUrl: null                // 原始审批表URL（用于比较是否发生变化）
    };

    this.resetForm("form");
  },

  isAllowedToTransfer(columnId) {
    const allowedColumns = [1, 7, 8, 10, 11];
    return allowedColumns.includes(Number(columnId));
  },
  /** 将文章转到头条（toutiao） */
  handleTransferToToutiao(row) {
    // 0. 先检查是否允许加入头条（支持栏目名=河道要闻 或 columnId 在白名单内）

    const isAllowed =
      row.name === '河道要闻' ||
      this.isAllowedToTransfer(row.columnId);

    if (!isAllowed) {
      this.$modal.msgError("该文章不能作为头条");
      return;
    }

    // 1. 查询当前是否有头条
    listToutiao().then(res => {
        const existingTop = res.rows && res.rows[0];

        if (existingTop) {
          // 已有头条 → 提示是否替换
          this.$modal.confirm('已有头条，是否替换？').then(() => {
            // 删除旧头条
            delToutiao(existingTop.id).then(() => {
              // 添加新头条
              this.doAddToutiao(row);
            }).catch(() => {
              this.$modal.msgError("删除旧头条失败");
            });
          }).catch(() => {
            // 用户取消替换
          });
        } else {
          // 没有头条 → 直接添加
          this.doAddToutiao(row);
        }
    });
  },

  /** 实际执行添加到 toutiao */
  doAddToutiao(row) {
    const transferData = { ...row };

    addToutiao(transferData).then(response => {
      this.$modal.msgSuccess("成功设为头条");
      // 可选：刷新 toutiao 列表或跳转页面
    }).catch(error => {
      this.$modal.msgError("设置头条失败，请重试");
      console.error('请求失败:', error);
    });
  },


  /**
   * 用户选择封面图片
  */
  selectCoverImage(imageUrl) {
    this.selectedCoverImage = imageUrl;

    // 不再立即关闭弹窗和上传图片，而是让用户点击确定按钮后再处理
    // this.coverDialogVisible = false;
    // this.uploadCoverImage(this.selectedCoverImage);
  },
  /**
   * 上传封面图片
   */
  async uploadCoverImage(imageUrl) {
    try {
      // 检查是否为OSS图片URL
      if (imageUrl.includes('aliyuncs.com')) {
        // 对于OSS图片，直接使用URL而不需要下载
        // 创建一个虚拟的File对象用于后续处理
        const fileName = imageUrl.split('/').pop().split('?')[0]; // 获取文件名并移除查询参数
        const file = new File([], fileName, { type: 'image/jpeg' }); // 创建一个空的File对象
        file.url = imageUrl; // 将原始URL附加到文件对象上

        // 直接使用该URL作为封面路径
        this.form.coverPath = imageUrl;

        // 如果是在转到河道要闻的过程中上传封面，则继续执行转到河道要闻的逻辑
        if (this.transferRow) {
          this.doAddRiverNewsAfterCoverUpload(this.transferRow);
        }
      } else {
        // 下载图片并转换为 File 对象（原有逻辑）
        const response = await fetch(imageUrl);
        const blob = await response.blob();
        const fileName = imageUrl.split('/').pop(); // 获取文件名
        const file = new File([blob], fileName, { type: blob.type });

        // 调用现有上传方法
        this.uploadFile = file;
        console.log('提交前压缩封面图片');
        this.uploadFile = await this.compressImage(this.uploadFile);
        await this.uploadFileToServer(this.uploadFile);
      }

    } catch (error) {
      console.error('封面图片上传失败:', error);
      this.$message.error('封面图片上传失败: ' + error.message);
    }
  },

/**
 * 封面图片上传成功后，执行转到河道要闻逻辑
 */
  doAddRiverNewsAfterCoverUpload(row) {
    // 防止重复提交
    if (this.isSubmitting) {
      this.$modal.msgWarning("数据正在处理，请勿重复提交");
      return;
    }

    this.isSubmitting = true;

    // 构造完整的数据对象，包含封面路径
    const transferData = {
      ...row,
      coverPath: this.form.coverPath // 使用上传后的封面路径
    };

    addRiver_news(transferData).then(response => {
      this.$modal.msgSuccess("成功设为河道要闻");
      this.getList();
      this.isSubmitting = false;
      // 清空transferRow，防止重复提交
      this.transferRow = null;
    }).catch(error => {
      this.$modal.msgError("设置河道要闻失败，请重试");
      console.error('请求失败:', error);
      this.isSubmitting = false;
    });
  },

  /** 将文章转到 river_news */
  handleTransferToNews(row) {
    // 提示是否执行
    this.$modal.confirm('是否将文章转到河道要闻？').then(() => {
      // 0. 判断是否允许转出到 river_news

      if (!this.isAllowedToTransfer(row.columnId)) {
        this.$modal.msgError("该栏目不允许转到河道要闻");
        return;
      }

      // 1. 检查文章内容中是否有图片
      const images = this.extractImagesFromContent(row.content);

      // 2. 查询是否已有相同标题的文章
      listRiver_news().then(res => {
        const existing = res.rows.find(item => item.title === row.title);
        if (existing) {
          this.$modal.msgError("该文章已存在，不能重复添加");
          return;
        }
        //检查是否超过8条数据
        // else if (res.total >= 8) {
        //   this.$modal.msgError("最多只能添加8条数据");
        //   return;
        // }

        // 3. 显示封面图片选择对话框
        this.articleImages = images;
        this.selectedCoverImage = null; // 用户选择的封面图片
        this.uploadFile = null; // 手动上传的封面图片
        this.transferRow = row;
        this.coverDialogVisible = true;
      });
    }).catch(() => {
      // 用户取消操作
    });
  },


   /** 实际执行添加到 river_news 列表 */
  doAddRiverNews(row) {
    const transferData = { ...row };

    addRiver_news(transferData).then(response => {
      this.$modal.msgSuccess("成功设为河道要闻");
      // 可选：刷新 toutiao 列表或跳转页面
    }).catch(error => {
      this.$modal.msgError("设置河道要闻失败，请重试");
      console.error('请求失败:', error);
    });
  },

  /** 搜索按钮操作 */
  // handleQuery() {
  //   this.queryParams.pageNum = 1;
  //   this.getList();
  //   this.getColumnList();
  // },
  handleQuery() {
    this.queryParams.pageNum = 1;

    // 确保content参数作为整体字符串传递，不进行分词
    if (this.queryParams.content) {
      // 移除前后空格并确保不为空
      this.queryParams.content = this.queryParams.content.trim();
    }

    // 添加日期范围参数
    if (this.dateRange && this.dateRange.length === 2) {
      this.queryParams.beginPubdate = this.dateRange[0];
      this.queryParams.endPubdate = this.dateRange[1];
    } else {
      this.queryParams.beginPubdate = undefined;
      this.queryParams.endPubdate = undefined;
    }

    this.getList();
  },

    /** 重置按钮操作 */
  resetQuery() {
    this.resetForm("queryForm");
    this.dateRange = [];
    this.queryParams.beginPubdate = undefined;
    this.queryParams.endPubdate = undefined;
    this.handleQuery();
  },
  // 多选框选中数据
  handleSelectionChange(selection) {
    this.ids = selection.map(item => item.articleId)
    this.single = selection.length !== 1
    this.multiple = !selection.length
  },
  /** 新增按钮操作 */
  handleAdd() {
    this.reset();
    //this.form.author=this.userName; //责任编辑手动输入
    this.form.articleOrigin = this.dept;
    this.open = true;
    this.title = "添加文章";
  },
  handleHttpRequest(options) {
    console.log('封面上传请求处理:', options);
    this.uploadFileToServer(options.file);
  },

  // 修改后的上传方法
  async uploadFileToServer(file) {
    try {
      // 检查是否为虚拟File对象（带有url属性的OSS图片）
      if (file.url) {
        // 对于OSS图片，直接使用URL
        this.form.coverPath = file.url;
        this.$message.success('封面图片设置成功');

        // 如果是在转到河道要闻的过程中上传封面，则继续执行转到河道要闻的逻辑
        if (this.transferRow) {
          this.doAddRiverNewsAfterCoverUpload(this.transferRow);
        }

        return { code: 200, url: file.url };
      } else {
        // 压缩图片
        console.log('提交前压缩封面图片');
        const compressedFile = await this.compressImage(file);

        const formData = new FormData();
        formData.append('file', compressedFile);

        console.log('调用封面上传API，ID:', this.form.articleId || 0);
        const response = await uploadFile(this.form.articleId || 0, formData);

        console.log('封面上传响应:', response);
        if (response.code === 200) {
          this.form.coverPath = response.url;
          this.$message.success('封面图片上传成功');

          // 如果是在转到河道要闻的过程中上传封面，则继续执行转到河道要闻的逻辑
          if (this.transferRow) {
            this.doAddRiverNewsAfterCoverUpload(this.transferRow);
          }

          return response;
        } else {
          throw new Error(response.msg || '上传失败');
        }
      }
    } catch (error) {
      console.error('上传失败:', error);
      this.$message.error('封面图片上传失败: ' + error.message);
      throw error;
    }
  },


  handleUpdate(row) {
    this.reset();
    const articleId = row.articleId || this.ids;//||是为了单选和多选都可以修改
    let columnId=row.columnId;

    getArticle(articleId).then(response => {
      this.form = response.data;
      columnId=this.form.columnId;
      getConlumn(columnId).then(response => {
        this.articleName = response.data.name;
      });
      console.log('获取文章数据:', this.form);

      // 如果是市局用户（canAdd为true），将文章来源添加到历史记录中
      if (this.canAdd && this.form.articleOrigin) {
        this.addToSourceHistory(this.form.articleOrigin);
      }

      // 如果author为空，则设置当前用户为作者
      if (!this.form.author) {
        this.form.author = this.userName;
      }

      // 将责任编辑添加到历史记录中
      if (this.form.author) {
        this.addToAuthorHistory(this.form.author);
      }

      const column = this.columnOptions.find(item => item.id === this.form.columnId);
      this.form.name = column ? column.name : '';
      this.open = true;
      this.title = "修改文章";

      // 初始化文件列表
      if (this.form.coverPath) {
        this.fileList = [{
          name: '封面图片',
          url: this.form.coverPath
        }];
      } else {
        this.fileList = [];
        this.uploadFile=null;
      }

      // 初始化审批表文件列表
      if (this.form.appval) {
        this.appvalFileList = [{
          name: '审批表',
          url: this.form.appval
        }];
        //console.log('初始化审批表文件列表:', this.appvalFileList);
      } else {
        this.appvalFileList = [];
        this.uploadAppvalFile=null;
        console.log('清空审批表文件列表');
      }

      // 初始化附件文件列表
      if (this.form.attachment) {
        this.attachmentFileList = [{
          name: this.getAttachmentFileName(this.form.attachment),
          url: this.form.attachment
        }];
      } else {
        this.attachmentFileList = [];
        this.uploadAttachmentFile=null;
        console.log('清空附件文件列表');
      }


      // 同步副标题状态 - 修改部分1：初始化时检查已有的副标题
      this.subtitles = [];
      // 检查是否存在副标题1，如果存在则添加到显示列表
      if (this.form.littleTitle1 || this.form.little_title1) {
        this.subtitles.push('littleTitle1');
      }
      // 检查是否存在副标题2，如果存在则添加到显示列表
      if (this.form.littleTitle2 || this.form.little_title2) {
        this.subtitles.push('littleTitle2');
      }
      // 如果没有任何副标题但允许添加，则默认显示一个空的副标题输入框
      if (this.subtitles.length === 0) {
        this.subtitles.push('littleTitle1');
      }

    });


  },

  handleUploadSuccess(response, file, fileList) {
    if (response.code === 200) {
      this.form.coverPath = response.data.url;
      this.$message.success('上传成功');
    } else {
      this.$message.error(response.msg || '上传失败');
    }
  },


  handleColumnChange(selectedName) {
    console.log('handleColumnChange', selectedName);
    if (selectedName) {
      const selectedColumn = this.columnOptions.find(item => item.name === selectedName);
      this.form.columnId = selectedColumn ? selectedColumn.id : null;
      this.form.name = selectedName;
      this.articleName = selectedName;
    } else {
      this.form.columnId = null;
      this.form.name = '';
      this.articleName = '';
    }
    // 强制重新渲染
    this.$nextTick(() => {
      this.selectKey += 1;
    });
  },

  /** 提交按钮 */
  async submitForm() {
    this.$refs["form"].validate(async valid => {
      if (!valid) return;


      try {

        // console.log('提交前检查 - uploadFile:', this.uploadFile);
        // console.log('提交前检查 - uploadAppvalFile:', this.uploadAppvalFile);
        // console.log('提交前检查 - uploadAppvalFile 类型:', typeof this.uploadAppvalFile);
        // console.log('提交前检查 - uploadAppvalFile 是否为 File:', this.uploadAppvalFile instanceof File);
        // console.log('提交前检查 - uploadAppvalFile 是否为真值:', !!this.uploadAppvalFile);
        // console.log('提交前检查 - fileList:', this.fileList);
        // console.log('提交前检查 - appvalFileList:', this.appvalFileList);

        // 检查是否有文件需要上传，如果有则显示加载提示
        const hasFilesToUpload = this.uploadFile || (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) || (this.uploadAttachmentFile && this.uploadAttachmentFile instanceof File);
        let loadingInstance = null;

        if (hasFilesToUpload) {
          loadingInstance = this.$loading({
            lock: true,
            text: '上传中请等待...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
        }

        // 1. 处理封面上传
        if (this.uploadFile) {
          console.log('处理封面上传');
          console.log('提交前压缩封面图片');
          this.uploadFile = await this.compressImage(this.uploadFile);
          await this.uploadFileToServer(this.uploadFile);
        } else {
          console.log('跳过封面上传 - 没有选择封面文件');
        }

        // 2. 处理审批表上传
        const hasAppvalFile = !!this.uploadAppvalFile;
        const isAppvalFileValid = this.uploadAppvalFile instanceof File;


        if (hasAppvalFile && isAppvalFileValid) {
          console.log('处理审批表上传');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);
          const appvalResult = await this.uploadAppvalToServer(this.uploadAppvalFile);
          // 确保审批表URL被正确设置到表单中
          if (appvalResult && appvalResult.code === 200) {
            this.form.appval = appvalResult.url;
          }
        } else {
          console.log('跳过审批表上传 - 条件不满足');
          // console.log('uploadAppvalFile 值:', this.uploadAppvalFile);
          // console.log('uploadAppvalFile 类型:', typeof this.uploadAppvalFile);
        }

        // 3. 处理附件上传
        // 将临时附件URL保存到表单中
        if (this.temporaryAttachmentUrl) {
          console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
          this.form.attachment = this.temporaryAttachmentUrl;
        } else if (this.form.attachment === undefined) {
          // 如果没有附件且form.attachment未定义，设置为null
          this.form.attachment = null;
        }
        console.log('最终使用的附件URL:', this.form.attachment);

        // 如果是市局用户（canAdd为true），将文章来源添加到历史记录中
        if (this.canAdd && this.form.articleOrigin) {
          this.addToSourceHistory(this.form.articleOrigin);
        }

        // 将责任编辑添加到历史记录中
        if (this.form.author) {
          this.addToAuthorHistory(this.form.author);
        }

        // 3. 处理文章内容中的本地图片上传到OSS
        if (this.form.content) {
          console.log('处理文章内容中的本地图片上传到OSS');
          try {
            // 直接使用正则表达式替换本地图片路径
            const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
            let match;
            const processedPaths = new Set();

            // 找到所有本地图片路径并上传到OSS
            while ((match = localImageRegex.exec(this.form.content)) !== null) {
              const fullImgTag = match[0];
              const localPath = match[1];

              // 避免重复处理
              if (processedPaths.has(localPath)) {
                continue;
              }
              processedPaths.add(localPath);

              try {
                // 获取图片并上传到OSS
                const response = await fetch(localPath);
                const blob = await response.blob();
                const fileName = localPath.split('/').pop() || `content_image_${Date.now()}.jpg`;
                const file = new File([blob], fileName, { type: blob.type });

                // 压缩图片
                console.log('提交前压缩文章内容图片');
                const compressedFile = await this.compressImage(file);

                // 上传到OSS
                const uploadResult = await uploadContentImage(compressedFile);
                if (uploadResult.code === 200) {
                  // 替换HTML中的路径
                  const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                  this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), uploadResult.url);
                  console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                }
              } catch (uploadError) {
                console.error('图片上传失败:', uploadError);
              }
            }
          } catch (error) {
            console.error('处理文章内容图片失败:', error);
            this.$message.warning('文章内容中的本地图片处理失败，将保存原始内容');
          }
        }

        // 检查是否上传了审批表
        if (!this.form.appval || this.form.appval === "") {
          this.$modal.msgError("请上传审批表");
          return;
        }
        // 4. 提交表单数据前，确保获取到编辑器的最新内容
        // 特别是图片调整大小后的状态
        if (this.$refs.form && this.form.content) {
          // 确保从编辑器获取最新内容
          const editorContent = this.$refs.form.fields.find(field => field.prop === 'content');
          if (editorContent && editorContent.$children && editorContent.$children[0]) {
            const editor = editorContent.$children[0];
            if (editor.getContent) {
              this.form.content = editor.getContent();
            } else if (editor.Quill) {
              // 如果没有getContent方法，直接从Quill实例获取内容
              this.form.content = editor.$refs.editor.children[0].innerHTML;
            }
          }
        }

        console.log('提交表单数据:', this.form);
        const apiMethod = this.form.articleId ? updateArticle : addArticle;
        await apiMethod(this.form);
        // 关闭加载提示
        if (loadingInstance) {
          loadingInstance.close();
        }

        this.$modal.msgSuccess(this.form.articleId ? "修改成功" : "新增成功");
        this.open = false;
        this.getList();
      } catch (error) {
        console.error('操作失败:', error);
          // 发生错误时关闭加载提示
        if (this.$loading) {
          // 关闭所有加载实例
          const loadingInstances = document.querySelectorAll('.el-loading-mask');
          if (loadingInstances.length > 0) {
            this.$loading().close();
          }
        }
        this.$message.error(`操作失败: ${error.message}`);
      }
    });
  },
  // 文件上传前处理
  beforeUpload(file) {
    const isImage = file.type.startsWith('image/');
    const isLt1M = file.size / 1024 / 1024 < 1; // 检查是否小于1MB

    if (!isImage) {
      this.$message.error('只能上传图片文件!');
      return false;
    }
    if (isLt1M) {
      this.$message.error('图片大小不能小于1MB!');
      return false;
    }

    this.uploadFile = file;
    return false; // 阻止自动上传
  },

  // 文件变化处理
  handleFileChange(file, fileList) {
    console.log('封面文件变化处理:', file, fileList);
    if (fileList.length > 0) {
      this.uploadFile = fileList[0].raw;
      this.fileList = [fileList[fileList.length - 1]]; // 只保留最后一个文件
      console.log('更新 uploadFile:', this.uploadFile);
    } else {
      this.uploadFile = null;
      this.fileList = [];
      console.log('清空 uploadFile');
    }
  },

  // 文件移除处理
  handleRemove() {
    console.log('封面文件移除处理');
    this.uploadFile = null;
    this.form.coverPath = null;
    this.fileList = [];
    console.log('清空 uploadFile 和 coverPath');
  },

    /** 删除按钮操作 */
  handleDelete(row) {
    const articleIds = row.articleId || this.ids;
    this.$modal.confirm('是否确认删除artilce编号为"' + articleIds + '"的数据项？').then(function () {
      return delArticle(articleIds);
    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("删除成功");
    }).catch(() => {
    });
  },

  /** 隐藏文章 */
  handleHide(row) {
    const articleId = row.articleId;
    this.$modal.confirm('是否确认隐藏该文章？').then(() => {
      // 创建包含status字段的数据对象
      return hideArticle(articleId);
    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("隐藏成功");
    }).catch(() => {
    });
  },

  /** 显示文章 */
  handleShow(row) {
    const articleId = row.articleId;
    this.$modal.confirm('是否确认显示该文章？').then(() => {

      return showArticle(articleId);
    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("显示成功");
    }).catch(() => {
    });
  },

  /** 批量隐藏文章 */
  handleBatchHide() {
    this.$modal.confirm('是否确认隐藏选中的文章？').then(() => {

        return batchHideArticle(this.ids);

    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("批量隐藏成功");
    }).catch(() => {
    });
  },

  /** 批量显示文章 */
  handleBatchShow() {
    this.$modal.confirm('是否确认显示选中的文章？').then(() => {
      return batchShowArticle(this.ids);

    }).then(() => {
      this.getList();
      this.$modal.msgSuccess("批量显示成功");
    }).catch(() => {
    });
  },

  // 添加文章来源到历史记录 - 使用固定大小为10的循环缓冲区
  addToSourceHistory(source) {
    if (!source) return;

    // 从 localStorage 获取现有数据
    let storedHistory = [];
    const storedHistoryStr = localStorage.getItem('sourceHistory');
    if (storedHistoryStr) {
      try {
        storedHistory = JSON.parse(storedHistoryStr);
      } catch (e) {
        console.error('解析历史记录失败:', e);
        storedHistory = [];
      }
    }

    // 检查是否已存在
    const existingIndex = storedHistory.findIndex(item => item.value === source);
    if (existingIndex !== -1) {
      // 如果已存在，将其移到数组开头
      const existingItem = storedHistory.splice(existingIndex, 1)[0];
      storedHistory.unshift(existingItem);
    } else {
      // 如果不存在，添加到数组开头
      storedHistory.unshift({ value: source, timestamp: Date.now() });

      // 如果数组长度超过10，移除最后一个元素
      if (storedHistory.length > 10) {
        storedHistory.pop();
      }
    }

    // 更新 localStorage
    localStorage.setItem('sourceHistory', JSON.stringify(storedHistory));

    // 更新当前组件的 sourceHistory（只保存值）
    this.sourceHistory = storedHistory.map(item => item.value);
  },

  // 添加责任编辑到历史记录 - 使用固定大小为10的循环缓冲区
  addToAuthorHistory(author) {
    if (!author) return;

    // 从 localStorage 获取现有数据
    let storedHistory = [];
    const storedHistoryStr = localStorage.getItem('authorHistory');
    if (storedHistoryStr) {
      try {
        storedHistory = JSON.parse(storedHistoryStr);
      } catch (e) {
        console.error('解析历史记录失败:', e);
        storedHistory = [];
      }
    }

    // 检查是否已存在
    const existingIndex = storedHistory.findIndex(item => item.value === author);
    if (existingIndex !== -1) {
      // 如果已存在，将其移到数组开头
      const existingItem = storedHistory.splice(existingIndex, 1)[0];
      storedHistory.unshift(existingItem);
    } else {
      // 如果不存在，添加到数组开头
      storedHistory.unshift({ value: author, timestamp: Date.now() });

      // 如果数组长度超过10，移除最后一个元素
      if (storedHistory.length > 10) {
        storedHistory.pop();
      }
    }

    // 更新 localStorage
    localStorage.setItem('authorHistory', JSON.stringify(storedHistory));

    // 更新当前组件的 authorHistory（只保存值）
    this.authorHistory = storedHistory.map(item => item.value);
  },

  // 文章来源自动完成查询
  querySearchSource(queryString, cb) {
    // 从 localStorage 获取最新数据
    let storedHistory = [];
    const storedHistoryStr = localStorage.getItem('sourceHistory');
    if (storedHistoryStr) {
      try {
        storedHistory = JSON.parse(storedHistoryStr);
      } catch (e) {
        console.error('解析历史记录失败:', e);
        storedHistory = [];
      }
    }

    // 过滤掉超过3天的数据
    const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
    storedHistory = storedHistory.filter(item => item.timestamp > thirtyDaysAgo);

    // 提取值并过滤
    const historyValues = storedHistory.map(item => item.value);
    const results = queryString
      ? historyValues.filter(item => item.includes(queryString))
      : historyValues;

    cb(results.map(item => ({ value: item })));
  },

  // 责任编辑自动完成查询
  querySearchAuthor(queryString, cb) {
    // 从 localStorage 获取最新数据
    let storedHistory = [];
    const storedHistoryStr = localStorage.getItem('authorHistory');
    if (storedHistoryStr) {
      try {
        storedHistory = JSON.parse(storedHistoryStr);
      } catch (e) {
        console.error('解析历史记录失败:', e);
        storedHistory = [];
      }
    }

    // 过滤掉超过3天的数据
    const thirtyDaysAgo = Date.now() - (3 * 24 * 60 * 60 * 1000);
    storedHistory = storedHistory.filter(item => item.timestamp > thirtyDaysAgo);

    // 提取值并过滤
    const historyValues = storedHistory.map(item => item.value);
    const results = queryString
      ? historyValues.filter(item => item.includes(queryString))
      : historyValues;

    cb(results.map(item => ({ value: item })));
  },

  /**删除操作，不删除数据 */
  handleDeleteData(row) {
    const articleIds = row.articleId || this.ids;
    this.$modal.confirm('是否确认删除artilce编号为"' + articleIds + '"的数据项？').then(function () {
      return logicDeleteArticle(articleIds);
    }).then(() => {
      delArticle(articleIds).then(() => {
        this.getList();
      });
      this.$modal.msgSuccess("删除成功");
    }).catch(() => {
      this.$modal.msgError("删除失败");
    });
  },
  /** 导出按钮操作 */
  handleExport() {
    this.download('article/article/export', {
      ...this.queryParams
    }, `article_${new Date().getTime()}.xlsx`)
  },

  /** 保存草稿 */
  async handleSaveDraft() {
    this.$refs["form"].validate(async valid => {
      if (!valid) return;

      // 对于草稿箱，我们不需要强制验证审批表
      // 但在保存前仍需要处理审批表的上传逻辑
      try {
        // 检查是否有文件需要上传
        const hasFilesToUpload = this.uploadFile || this.needUploadAppval();
        let loadingInstance = null;

        if (hasFilesToUpload) {
          loadingInstance = this.$loading({
            lock: true,
            text: '上传中请等待...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
        }

        // 1. 处理封面上传
        if (this.uploadFile) {
          console.log('处理封面上传');
          this.uploadFile = await this.compressImage(this.uploadFile);
          await this.uploadFileToServer(this.uploadFile);
        } else {
          console.log('跳过封面上传 - 没有选择封面文件');
        }

        // 2. 处理审批表上传（如果有的话）
        if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
          console.log('处理审批表上传');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);
          const response = await this.uploadAppvalToServer(this.uploadAppvalFile);

          // 更新审批表状态
          if (response && response.url) {
            this.appvalState.currentUrl = response.url;
            this.appvalState.pendingFile = null;
            this.appvalState.isRemoved = false;
            this.appvalState.originalUrl = response.url; // 同步originalUrl
            this.form.appval = response.url; // 确保form.appval也被更新
          }
        }
        // 检查用户是否移除了审批表
        else if (this.appvalState.isRemoved) {
          console.log('用户移除了审批表，清空appval字段');
          this.form.appval = null;
          // 确保状态同步到appvalState
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
        }

        // 3. 处理附件上传（如果有的话）
        // 将临时附件URL保存到表单中
        if (this.temporaryAttachmentUrl) {
          console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
          this.form.attachment = this.temporaryAttachmentUrl;
        } else if (this.form.attachment === undefined) {
          // 如果没有附件且form.attachment未定义，设置为null
          this.form.attachment = null;
        }
        console.log('最终使用的附件URL:', this.form.attachment);

        // 3. 处理文章内容中的本地图片上传到OSS
        if (this.form.content) {
          console.log("处理文章内容中的本地图片上传到OSS");
          try {
            // 直接使用正则表达式替换本地图片路径
            const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
            let match;
            const processedPaths = new Set();

            // 找到所有本地图片路径并上传到OSS
            while ((match = localImageRegex.exec(this.form.content)) !== null) {
              const fullImgTag = match[0];
              const localPath = match[1];

              // 避免重复处理
              if (processedPaths.has(localPath)) {
                continue;
              }
              processedPaths.add(localPath);

              try {
                // 获取图片并上传到OSS
                const response = await fetch(localPath);
                const blob = await response.blob();
                const fileName = localPath.split("/").pop() || `content_image_${Date.now()}.jpg`;
                const file = new File([blob], fileName, { type: blob.type });

                // 压缩图片
                console.log("提交前压缩文章内容图片");
                const compressedFile = await this.compressImage(file);

                // 上传到OSS
                const uploadResult = await uploadContentImage(compressedFile);
                if (uploadResult.code === 200) {
                  // 替换HTML中的路径
                  const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                  this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), uploadResult.url);
                  console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                }
              } catch (uploadError) {
                console.error("图片上传失败:", uploadError);
              }
            }
          } catch (error) {
            console.error("处理文章内容图片失败:", error);
            this.$message.warning("文章内容中的本地图片处理失败，将保存原始内容");
          }
        }

        // 4. 保存草稿逻辑前的最终审批表状态检查
        console.log('保存草稿前最终审批表状态检查:', {
          formAppval: this.form.appval,
          currentUrl: this.appvalState.currentUrl,
          originalUrl: this.appvalState.originalUrl,
          isRemoved: this.appvalState.isRemoved
        });

        // 确保审批表状态正确同步
        if (this.appvalState.isRemoved) {
          // 如果审批表被标记为已移除，确保form.appval为空
          this.form.appval = null;
          console.log('审批表已被移除，清空form.appval');
        } else if (this.appvalState.currentUrl && !this.form.appval) {
          // 如果currentUrl存在但form.appval为空，同步状态
          this.form.appval = this.appvalState.currentUrl;
          console.log('强制同步审批表状态到form.appval');
        }

        // 创建草稿数据
        const draftData = { ...this.form };
        draftData.status = 0; // 草稿状态

        // 添加调试日志，确认draftData中appval的值
        console.log('准备保存草稿，draftData内容:', draftData);
        console.log('draftData中appval的值:', draftData.appval);

        // 如果是从已发布的文章编辑并保存到草稿箱
        if (this.form.articleId && this.title === "修改文章") {
          try {
            // 删除已有的文章（从article表中删除）
            try {
              await delArticle(this.form.articleId);
            } catch (deleteError) {
              // 如果删除失败，记录日志但不中断操作，不显示错误提醒
              console.warn('删除article文章时出错:', deleteError.message);
              // 不显示错误提醒给用户
            }

            // 保存到草稿箱
            await saveDraft(draftData);
          } catch (error) {
            console.error("保存草稿失败:", error);
            // 不向用户显示错误，只记录日志
            console.warn("保存草稿失败（不向用户显示）:", error.message);
            // 不重新抛出错误，避免向用户显示错误提示
            return;
          }
        } else {
          if (!draftData.title || !draftData.columnId || !draftData.content) {
            this.$message.error("标题、栏目名称或内容不能为空");
            return;
          }

          try {
            if (this.form.articleId) {
              await updateDraft(draftData);
            } else {
              await saveDraft(draftData);
            }
          } catch (draftError) {
            console.error("草稿保存失败:", draftError);
            this.$message.error(`草稿保存失败: ${draftError.message}`);
            throw draftError; // 重新抛出错误以便上层捕获
          }
        }

        // 关闭加载提示
        if (loadingInstance) {
          loadingInstance.close();
        }

        this.$modal.msgSuccess("草稿保存成功");
        this.open = false;
        this.loadDraftList(); // 重新加载草稿列表
        this.getList(); // 重新加载主列表
        // 保存草稿后打开草稿箱列表
        this.draftBoxVisible = true;

      } catch (error) {
        console.error('保存草稿失败:', error);
        // 不向用户显示错误，只记录日志
        console.warn("保存草稿失败（不向用户显示）:", error.message);
      } finally {
        // 发生错误时关闭加载提示
        if (this.$loading) {
          // 关闭所有加载实例
          const loadingInstances = document.querySelectorAll('.el-loading-mask');
          if (loadingInstances.length > 0) {
            this.$loading().close();
          }
        }
      }
    });
  },

  /** 打开草稿箱 */
  handleOpenDraftBox() {
    this.draftBoxVisible = true;
    this.loadDraftList();
  },

  /** 加载草稿列表 */
  loadDraftList() {
    this.draftLoading = true;
    // 从API获取草稿列表
    listDraft().then(response => {
      this.draftList = response.rows;
      // 处理栏目名称映射
      this.draftList = this.draftList.map(item => {
        const conlumn = this.columnOptions.find(col => col.id === item.columnId);
        return {
          ...item,
          name: conlumn ? conlumn.name : '未知栏目',
        };
      });
      this.draftLoading = false;
    }).catch(error => {
      console.error('获取草稿列表失败:', error);
      this.draftLoading = false;
      this.$message.error('获取草稿列表失败');
    });
  },

  /** 编辑草稿 */
  handleEditDraft(row) {
    this.reset();
    const articleId = row.articleId;
    getDraft(articleId).then(response => {
      this.form = response.data;
      console.log("获取草稿数据:", this.form);

      // 如果author为空，则设置当前用户为作者
      if (!this.form.author) {
        this.form.author = this.userName;
      }
      const column = this.columnOptions.find(item => item.id === this.form.columnId);
      this.form.name = column ? column.name : "";
      this.open = true;
      this.title = "修改草稿";

      // 初始化文件列表
      if (this.form.coverPath) {
        this.fileList = [{
          name: "封面图片",
          url: this.form.coverPath
        }];
      } else {
        this.fileList = [];
        this.uploadFile=null;
      }

      // 初始化审批表文件列表和状态管理字段
      if (this.form.appval) {
        this.appvalFileList = [{
          name: "审批表",
          url: this.form.appval
        }];
        // 设置uploadAppvalFile为null，因为我们是从URL加载的
        // 但在重新上传时需要能够检测到变化
        this.uploadAppvalFile = null;

        // 初始化审批表状态管理字段
        this.appvalState.currentUrl = this.form.appval;
        this.appvalState.originalUrl = this.form.appval;
        this.appvalState.isRemoved = false;
        this.appvalState.pendingFile = null;

        console.log("初始化审批表文件列表和状态:", {
          fileList: this.appvalFileList,
          currentUrl: this.appvalState.currentUrl,
          originalUrl: this.appvalState.originalUrl,
          isRemoved: this.appvalState.isRemoved
        });
      } else {
        this.appvalFileList = [];
        this.uploadAppvalFile = null;

        // 初始化审批表状态管理字段为空
        this.appvalState.currentUrl = null;
        this.appvalState.originalUrl = null;
        this.appvalState.isRemoved = false;
        this.appvalState.pendingFile = null;

        console.log("清空审批表文件列表和状态");
      }

      // 初始化附件文件列表
      if (this.form.attachment) {
        this.attachmentFileList = [{
          name: this.getAttachmentFileName(this.form.attachment),
          url: this.form.attachment
        }];
        this.uploadAttachmentFile = null;
        console.log("初始化附件文件列表");
      } else {
        this.attachmentFileList = [];
        this.uploadAttachmentFile = null;
        console.log("清空附件文件列表");
      }

      // 同步副标题状态 - 修改部分1：初始化时检查已有的副标题
      this.subtitles = [];
      // 检查是否存在副标题1，如果存在则添加到显示列表
      if (this.form.littleTitle1 || this.form.little_title1) {
        this.subtitles.push("littleTitle1");
      }
      // 检查是否存在副标题2，如果存在则添加到显示列表
      if (this.form.littleTitle2 || this.form.little_title2) {
        this.subtitles.push("littleTitle2");
      }
      // 如果没有任何副标题但允许添加，则默认显示一个空的副标题输入框
      if (this.subtitles.length === 0) {
        this.subtitles.push("littleTitle1");
      }

    });
  },

  /** 发布草稿 */
  handlePublishDraft(row) {
    // 检查是否上传了审批表
    if (!row.appval || row.appval === "") {
      this.$modal.msgError("请上传审批表后再发布");
      return;
    }

    this.$modal.confirm('是否确认发布该草稿？').then(() => {
      return publishDraft(row.articleId);
    }).then(() => {
      this.$modal.msgSuccess("发布成功");
      this.loadDraftList();
      this.getList(); // 刷新文章列表
      // 发布成功后关闭草稿箱列表弹窗
      this.draftBoxVisible = false;
    }).catch(() => {
      // 用户取消操作
    });
  },

  /** 删除草稿 */
  handleDeleteDraft(row) {
    this.$modal.confirm('是否确认删除该草稿？').then(() => {
      return delDraft(row.articleId);
    }).then(() => {
      this.$modal.msgSuccess("删除成功");
      this.loadDraftList();
    }).catch(() => {
      // 用户取消操作
    });
  },

  /** 更新草稿 */
  async handleUpdateDraft() {
    this.$refs["form"].validate(async valid => {
      if (!valid) return;

      try {
        // 检查是否有文件需要上传
        const hasFilesToUpload = this.uploadFile || this.needUploadAppval();
        let loadingInstance = null;

        if (hasFilesToUpload) {
          loadingInstance = this.$loading({
            lock: true,
            text: '上传中请等待...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
        }

        // 1. 处理封面上传
        if (this.uploadFile) {
          console.log('处理封面上传');
          this.uploadFile = await this.compressImage(this.uploadFile);
          await this.uploadFileToServer(this.uploadFile);
        } else {
          console.log('跳过封面上传 - 没有选择封面文件');
        }

        // 2. 处理审批表上传
        // 检查是否有新的审批表文件需要上传
        if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
          console.log('处理审批表上传');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);
          const response = await this.uploadAppvalToServer(this.uploadAppvalFile);

          // 更新审批表状态
          if (response && response.url) {
            this.appvalState.currentUrl = response.url;
            this.appvalState.pendingFile = null;
            this.appvalState.isRemoved = false;
            this.appvalState.originalUrl = response.url; // 同步originalUrl
            this.form.appval = response.url; // 确保form.appval也被更新
          }
        }
        // 检查用户是否移除了审批表
        else if (this.appvalState.isRemoved) {
          console.log('用户移除了审批表，清空appval字段');
          this.form.appval = null;
          // 确保状态同步到appvalState
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
        }

        // 3. 处理附件上传
        // 将临时附件URL保存到表单中
        if (this.temporaryAttachmentUrl) {
          console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
          this.form.attachment = this.temporaryAttachmentUrl;
        } else if (this.form.attachment === undefined) {
          // 如果没有附件且form.attachment未定义，设置为null
          this.form.attachment = null;
        }
        console.log('最终使用的附件URL:', this.form.attachment);

        // 3. 处理文章内容中的本地图片上传到OSS
        if (this.form.content) {
          console.log("处理文章内容中的本地图片上传到OSS");
          try {
            // 直接使用正则表达式替换本地图片路径
            const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
            let match;
            const processedPaths = new Set();

            // 找到所有本地图片路径并上传到OSS
            while ((match = localImageRegex.exec(this.form.content)) !== null) {
              const fullImgTag = match[0];
              const localPath = match[1];

              // 避免重复处理
              if (processedPaths.has(localPath)) {
                continue;
              }
              processedPaths.add(localPath);

              try {
                // 获取图片并上传到OSS
                const response = await fetch(localPath);
                const blob = await response.blob();
                const fileName = localPath.split("/").pop() || `content_image_${Date.now()}.jpg`;
                const file = new File([blob], fileName, { type: blob.type });

                // 压缩图片
                console.log("提交前压缩文章内容图片");
                const compressedFile = await this.compressImage(file);

                // 上传到OSS
                const uploadResult = await uploadContentImage(compressedFile);
                if (uploadResult.code === 200) {
                  // 替换HTML中的路径
                  const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                  this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), uploadResult.url);
                  console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                }
              } catch (uploadError) {
                console.error("图片上传失败:", uploadError);
              }
            }
          } catch (error) {
            console.error("处理文章内容图片失败:", error);
            this.$message.warning("文章内容中的本地图片处理失败，将保存原始内容");
          }
        }

        // 4. 更新草稿逻辑前的最终审批表状态检查
        console.log('更新草稿前最终审批表状态检查:', {
          formAppval: this.form.appval,
          currentUrl: this.appvalState.currentUrl,
          originalUrl: this.appvalState.originalUrl,
          isRemoved: this.appvalState.isRemoved
        });

        // 确保审批表状态正确同步
        if (this.appvalState.isRemoved) {
          // 如果审批表被标记为已移除，确保form.appval为空
          this.form.appval = null;
          console.log('审批表已被移除，清空form.appval');
        } else if (this.appvalState.currentUrl && !this.form.appval) {
          // 如果currentUrl存在但form.appval为空，同步状态
          this.form.appval = this.appvalState.currentUrl;
          console.log('强制同步审批表状态到form.appval');
        }

        // 更新草稿逻辑
        const draftData = { ...this.form };
        draftData.status = 0; // 草稿状态

        // 添加调试日志，确认draftData中appval的值
        console.log('准备更新草稿，draftData内容:', draftData);
        console.log('draftData中appval的值:', draftData.appval);

        if (this.form.articleId) {
          // 更新草稿
          await updateDraft(draftData);
        } else {
          // 新增草稿
          await saveDraft(draftData);
        }

        // 关闭加载提示
        if (loadingInstance) {
          loadingInstance.close();
        }

        this.$modal.msgSuccess("草稿更新成功");
        this.open = false;
        this.loadDraftList(); // 重新加载草稿列表
        // 更新草稿后不关闭草稿箱列表弹窗

      }catch (error) {
        console.error('更新草稿失败:', error);
        this.$message.error(`更新草稿失败: ${error.message}`);
      } finally {
        // 发生错误时关闭加载提示
        if (this.$loading) {
          // 关闭所有加载实例
          const loadingInstances = document.querySelectorAll('.el-loading-mask');
          if (loadingInstances.length > 0) {
            this.$loading().close();
          }
        }
      }
    });
  },

  /** 从草稿直接发布 */
  async handlePublishFromDraft() {
    try {
      // 显示加载提示
      const loadingInstance = this.$loading({
        lock: true,
        text: '发布中，请稍候...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });

      try{
        console.log('开始从草稿直接发布，当前审批表状态:', {
          formAppval: this.form.appval,
          currentUrl: this.appvalState.currentUrl,
          originalUrl: this.appvalState.originalUrl,
          uploadAppvalFile: this.uploadAppvalFile,
          isRemoved: this.appvalState.isRemoved
        });

        // 检查是否有新的审批表文件需要上传
        if (this.uploadAppvalFile && this.uploadAppvalFile instanceof File) {
          console.log('检测到新的审批表文件，开始处理');
          console.log('提交前压缩审批表');
          this.uploadAppvalFile = await this.compressImage(this.uploadAppvalFile, false);

          // 上传审批表
          const response = await this.uploadAppvalToServer(this.uploadAppvalFile);

          // 更新审批表状态
          if (response && response.url) {
            console.log('审批表上传成功:', response.url);
            this.appvalState.currentUrl = response.url;
            this.appvalState.pendingFile = null;
            this.appvalState.isRemoved = false;
            this.appvalState.originalUrl = response.url;
            this.form.appval = response.url;

            // 强制同步状态
            this.$forceUpdate();
            await this.$nextTick();

            console.log('审批表状态已更新:', {
              currentUrl: this.appvalState.currentUrl,
              originalUrl: this.appvalState.originalUrl,
              formAppval: this.form.appval
            });
          }
        }
        // 检查用户是否移除了审批表
        else if (this.appvalState.isRemoved) {
          console.log('用户移除了审批表');
          this.form.appval = null;
          this.appvalState.currentUrl = null;
          this.appvalState.originalUrl = null;
        }
        // 如果已有审批表，确保状态同步
        else if (this.appvalState.originalUrl && !this.form.appval) {
          console.log('同步已有审批表状态');
          this.form.appval = this.appvalState.originalUrl;
        }

        // 验证审批表是否有效
        const isAppvalValid = this.isValidAppval();
        console.log('审批表验证结果:', isAppvalValid);

        if (!isAppvalValid) {
          this.$modal.msgError("请上传审批表");
          return;
        }

        console.log('审批表验证通过，准备发布草稿');

        // 再次确认审批表状态，确保使用最新的审批表
        console.log('发布前再次确认审批表状态:', {
          formAppval: this.form.appval,
          currentUrl: this.appvalState.currentUrl,
          originalUrl: this.appvalState.originalUrl,
          isRemoved: this.appvalState.isRemoved
        });

        // 确保form.appval是最新的
        if (this.appvalState.isRemoved) {
          this.form.appval = null;
        } else if (this.appvalState.currentUrl) {
          this.form.appval = this.appvalState.currentUrl;
        } else if (this.appvalState.originalUrl && !this.appvalState.isRemoved) {
          this.form.appval = this.appvalState.originalUrl;
        }

        console.log('最终使用的审批表URL:', this.form.appval);

        // 处理附件上传（如果有的话）
        // 将临时附件URL保存到表单中
        if (this.temporaryAttachmentUrl) {
          console.log('使用临时附件URL:', this.temporaryAttachmentUrl);
          this.form.attachment = this.temporaryAttachmentUrl;
          console.log('附件URL设置成功:', this.temporaryAttachmentUrl);
        } else if (this.form.attachment === undefined) {
          // 如果没有附件且form.attachment未定义，设置为null
          this.form.attachment = null;
        }
        console.log('最终使用的附件URL:', this.form.attachment);

        // 先更新草稿记录，确保审批表URL和附件URL被正确保存到数据库
        console.log('更新草稿记录，确保审批表URL和附件URL被保存到数据库');
        try {
          // 创建更新数据副本
          const updateData = { ...this.form };

          // 添加调试日志，确认updateData中appval和attachment的值
          console.log('准备更新草稿记录，updateData内容:', updateData);
          console.log('updateData中appval的值:', updateData.appval);
          console.log('updateData中attachment的值:', updateData.attachment);

          // 调用更新草稿接口
          const updateResponse = await updateDraft(updateData);
          if (updateResponse && updateResponse.code === 200) {
            console.log('草稿记录更新成功');
          } else {
            console.warn('草稿记录更新可能失败:', updateResponse);
          }
        } catch (updateError) {
          console.error('更新草稿记录时出错:', updateError);
          // 即使更新失败也继续发布流程
        }

        // 处理文章内容中的本地图片上传到OSS
        if (this.form.content) {
          console.log("处理文章内容中的本地图片上传到OSS");
          try {
            // 直接使用正则表达式替换本地图片路径
            const localImageRegex = /<img[^>]*src=["'](\/dev-api\/profile\/upload\/[^"']+)["'][^>]*>/g;
            let match;
            const processedPaths = new Set();

            // 找到所有本地图片路径并上传到OSS
            while ((match = localImageRegex.exec(this.form.content)) !== null) {
              const fullImgTag = match[0];
              const localPath = match[1];

              // 避免重复处理
              if (processedPaths.has(localPath)) {
                continue;
              }
              processedPaths.add(localPath);

              try {
                // 获取图片并上传到OSS
                const response = await fetch(localPath);
                const blob = await response.blob();
                const fileName = localPath.split("/").pop() || `content_image_${Date.now()}.jpg`;
                const file = new File([blob], fileName, { type: blob.type });

                // 压缩图片
                console.log("提交前压缩文章内容图片");
                const compressedFile = await this.compressImage(file);

                // 上传到OSS
                const uploadResult = await uploadContentImage(compressedFile);
                if (uploadResult.code === 200) {
                  // 替换HTML中的路径
                  const newImgTag = fullImgTag.replace(localPath, uploadResult.url);
                  this.form.content = this.form.content.replace(new RegExp(localPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), uploadResult.url);
                  console.log(`图片路径已替换: ${localPath} -> ${uploadResult.url}`);
                }
              } catch (uploadError) {
                console.error("图片上传失败:", uploadError);
              }
            }
          } catch (error) {
            console.error("处理文章内容图片失败:", error);
            this.$message.warning("文章内容中的本地图片处理失败，将保存原始内容");
          }
        }

        // 发布草稿
        const response = await publishDraft(this.form.articleId);
        if (response && response.code === 200) {
          this.$modal.msgSuccess("发布成功");
          this.open = false;
          this.loadDraftList();
          this.getList(); // 刷新文章列表
          // 发布成功后关闭草稿箱列表弹窗
          this.draftBoxVisible = false;
        } else {
          throw new Error(response.msg || "发布失败");
        }
      } finally {
        // 关闭加载提示
        loadingInstance.close();
      }

    }catch (error) {
      console.error("发布草稿失败:", error);
      this.$message.error(`发布草稿失败: ${error.message}`);
    }
  },
  }
}

</script>
<style scoped>
.content-cell {
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制显示两行 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5; /* 设置合适的行高 */
  max-height: 3em; /* 两行的高度，根据实际行高调整 */
}

.subtitle-item {
  margin-bottom: 20px;
}


.manual-cover-upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.image-item {
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s;
}

.image-item:hover {
  border-color: #409eff;
}

.image-item.selected {
  border-color: #409eff;
  box-shadow: 0 0 5px rgba(64, 158, 255, 0.5);
}

.cover-preview {
  width: 150px;
  height: 100px;
  object-fit: cover;
}

.cover-section-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.no-image-tip {
  color: #999;
  font-style: italic;
  padding: 20px 0;
  text-align: center;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.has-approval {
  color: #67c23a;
  font-weight: bold;
}

.no-approval {
  color: #f56c6c;
  font-weight: bold;
}

/* 草稿相关按钮样式 */
.draft-publish-button {
  font-weight: bold;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.draft-publish-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.draft-save-button {
  font-weight: bold;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.draft-save-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

</style>
